package com.emm.yixun.mobile.ui.personal;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.mobile.R;
import com.emm.yixun.mobile.adapter.PhoneSelectAdapter;
import com.emm.yixun.mobile.application.EmmApplication;
import com.emm.yixun.mobile.base.BaseActivity;
import com.emm.yixun.mobile.model.AddProblemFeedback;
import com.emm.yixun.mobile.model.AddpirModel;
import com.eroad.product.tools.MyGridView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nui.multiphotopicker.model.ImageItem;
import com.nui.multiphotopicker.view.ImageBucketChooseActivity;
import com.yanzhenjie.album.Album;
import com.yixun.app.viewpagerandimag.sample.ViewPagerActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import me.imid.swipebacklayout.lib.SwipeBackLayout;
import me.imid.swipebacklayout.lib.app.SwipeBackActivity;
import xf.tools.Loading;

/**
 * <p>
 * <b>Title：</b> 反馈界面
 * </p>
 * <p>
 * <b>Description：</b>
 * </p>
 *
 * @author tangxin
 * @date 2016年12月6日 下午4:12:11
 */
public class FeedBackActivity extends SwipeBackActivity {

    public static final String TAG = "FeedBackActivity";

    /**
     * 标题
     */
    TextView title_main;

    /**
     * 返回按钮
     */
    ImageView back_btn;

    /**
     * 待上传的图片列表
     */
    PhoneSelectAdapter adapter;

    ArrayList<AddpirModel> ap;

    /**
     * 添加图片
     */
    MyGridView grid_phone_up;

    /**
     * 反馈内容
     */
    EditText feed_content;

    /**
     * 提交按钮
     */
    Button up_btn;

    /**
     * 侧滑关闭框架
     */
    private SwipeBackLayout mSwipeBackLayout;

    /**
     * 头像菜单
     */
    public View view3;

    /**
     * 头像菜单
     */
    public PopupWindow popu_phone;

    /**
     * 拍照图片路径
     */
    private Uri mImageCaptureUri;

    /**
     * 拍照请求码
     */
    private static final int PICK_FROM_CAMERA = 1;

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);

        setContentView(R.layout.feedback);

        SetSwipeBackLayout(mSwipeBackLayout);

        BaseActivity.activity = this;

        initView();

        initBtn();
    }

    /**
     * <p>
     * <b>Title：</b> 初始化view
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 下午2:13:46
     */
    private void initView() {
        title_main = (TextView) findViewById(R.id.title_main);
        title_main.setText("意见反馈");
        back_btn = (ImageView) findViewById(R.id.back_btn);
        grid_phone_up = (MyGridView) findViewById(R.id.grid_phone_up);
        feed_content = (EditText) findViewById(R.id.feed_content);
        up_btn = (Button) findViewById(R.id.up_btn);
        SetRelativiLayoutPadding(R.id.main_head_top_rela);
    }

    /**
     * <p>
     * <b>Title：</b> 初始化监听事件
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 下午2:13:56
     */
    private void initBtn() {
        back_btn.setVisibility(View.VISIBLE);
        back_btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        SetDate();
        adapter = new PhoneSelectAdapter(FeedBackActivity.this, ap, 0);
        grid_phone_up.setAdapter(adapter);
        grid_phone_up.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if ("1".equals(ap.get(position).getType())) {
                    ViewPagerActivity.postion = position;
                    ViewPagerActivity.sDrawables.clear();
                    for (int u = 0; u < ap.size(); u++) {
                        if ("1".equals(ap.get(u).getType())) {
                            ViewPagerActivity.sDrawables.add("file://" + ap.get(u).getPath());
                        }
                    }
                    EmmApplication.IsMoreSelect = true;// 设置是否多选
                    EmmApplication.setData("Picture", "1");// 设置选择类型
                    EmmApplication.SelectNumber = 9;// 设置多选数量
                    Intent intent = new Intent(FeedBackActivity.this, ViewPagerActivity.class);
                    intent.putExtra("IsOpenDelete", 2);
                    startActivity(intent);
                }
            }
        });
        up_btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null == feed_content.getText().toString().trim()
                        || "".equals(feed_content.getText().toString().trim())
                        || TextUtils.isEmpty(feed_content.getText().toString().trim())) {
                    EmmApplication.Ts("还没有填写反馈内容");
                } else {
                    // 调用提交
                    Loading.showDialogForLoading(FeedBackActivity.this, "正在提交...", false, true, 100000);
                    RecordTaskUpdate record = new RecordTaskUpdate();
                    record.execute();
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        BaseActivity.activity = this;
        // 选择照片后返回此界面，给adapter赋值
        if (null != EmmApplication.pir || EmmApplication.pir.size() > 0) {
            if (null != ap) {
                ap.clear();
            } else {
                ap = new ArrayList<AddpirModel>();
            }
            for (int i = 0; i < EmmApplication.pir.size(); i++) {
                AddpirModel a = new AddpirModel();
                a.setIsnet("1");
                a.setType("1");
                a.setPath(EmmApplication.pir.get(i).sourcePath);
                ap.add(a);
            }
            AddpirModel a = new AddpirModel();
            a.setIsnet("1");
            a.setType("2");
            a.setPath("");
            ap.add(a);

            adapter.SetDate(ap);
        }
        // 接收适配器里发出的打开相册的广播
        IntentFilter filterr = new IntentFilter();
        filterr.addAction("open_Image_popu");
        registerReceiver(mBroadcastReceiver, filterr);
    }

    /**
     * 广播监听方法 当点击添加图片按钮时，接收到广播，弹出popupwindow
     */
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals("open_Image_popu")) {
                popu();
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mBroadcastReceiver);
        EmmApplication.pir.clear();
    }

    /**
     * <p>
     * <b>Title：</b> 添加一组默认数据
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 下午2:14:13
     */
    private void SetDate() {
        ap = new ArrayList<AddpirModel>();
        AddpirModel a = new AddpirModel();
        a.setIsnet("1");
        a.setType("2");
        a.setPath("");
        ap.add(a);
    }

    /**
     * <p>
     * <b>Title：</b> 点击添加图片按钮后的弹出框
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 下午3:32:06
     */
    public void popu() {
        view3 = LayoutInflater.from(FeedBackActivity.this).inflate(R.layout.item_popupwindow, null);
        popu_phone = new PopupWindow(view3, android.support.v4.view.ViewPager.LayoutParams.FILL_PARENT,
                android.support.v4.view.ViewPager.LayoutParams.FILL_PARENT);

        popu_phone.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
        popu_phone.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

        popu_phone.showAtLocation(view3, Gravity.BOTTOM, 0, 0);
        popu_phone.showAsDropDown(view3, 0, 0);
        popu_phone.setFocusable(true);
        popu_phone.setOutsideTouchable(true);
        view3.setFocusable(true);
        view3.setFocusableInTouchMode(true);

        view3.setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    popu_phone.dismiss();
                }
                return false;
            }
        });

        view3.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                popu_phone.dismiss();
            }
        });

        // 拍照
        Button item_popupwindows_camera = (Button) view3.findViewById(R.id.item_popupwindows_camera);
        // 相册
        Button item_popupwindows_Photo = (Button) view3.findViewById(R.id.item_popupwindows_Photo);
        // 取消
        Button item_popupwindows_cancel = (Button) view3.findViewById(R.id.item_popupwindows_cancel);

        item_popupwindows_cancel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                popu_phone.dismiss();
                EmmApplication.setLog(FeedBackActivity.this);
            }
        });
        item_popupwindows_camera.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                popu_phone.dismiss();
                Album.camera(activity).start(PICK_FROM_CAMERA);
            }
        });
        item_popupwindows_Photo.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                EmmApplication.bitmap = null;
                popu_phone.dismiss();
                EmmApplication.setData("Picture", "1");
                EmmApplication.IsMoreSelect = true;
                startActivity(new Intent(FeedBackActivity.this, ImageBucketChooseActivity.class));
            }
        });
    }

    public class problemImageListinfo {
        private String problemImage;// 反馈图片
        private String problemImageType;// 反馈图片类型

        public String getProblemImage() {
            return problemImage;
        }

        public void setProblemImage(String problemImage) {
            this.problemImage = problemImage;
        }

        public String getProblemImageType() {
            return problemImageType;
        }

        public void setProblemImageType(String problemImageType) {
            this.problemImageType = problemImageType;
        }
    }

    /**
     * 新增反馈
     */
    AddProblemFeedback addproblem;

    /**
     * <p>
     * <b>Title：</b> 新增反馈
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @param problemImageList
     * @author tangxin
     * @date 2016年12月7日 下午2:14:54
     */
    private void addProblemFeedback(ArrayList<problemImageListinfo> problemImageList) {
        EmmApplication.updateUrl("addProblemFeedback");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("version", EmmApplication.getPackageManager(5));
        map.put("merchantId", EmmApplication.getData(EmmApplication.merchantId));
        map.put("token", EmmApplication.getToken());
        map.put("userId", EmmApplication.getUserId());
        map.put("projectCode", EmmApplication.getProjectCode());
        map.put("terminalCode", EmmApplication.getPackageManager(2));
        map.put("problemContent", feed_content.getText().toString().trim());
        map.put("problemImageList", problemImageList);
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("params", map);
        JSONObject json = new JSONObject(paramsMap);
        String jsonstr = json.toString();
        RequestParams params = new RequestParams();
        params.put("body", jsonstr);
        Log.v("addProblemFeedback-->post", EmmApplication.urlStr + "?body=" + jsonstr);
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        asyncHttpClient.post(EmmApplication.urlStr, params, new AsyncHttpResponseHandler() {
            @Override
            public void onFailure(Throwable error, String content) {
                super.onFailure(error, content);
                Loading.hideDialogForLoading();
                Log.v(TAG, "请求结束error:" + error + "==" + content);
            }

            @Override
            public void onFinish() {
                Loading.hideDialogForLoading();
                Log.v(TAG, "请求结束");
                super.onFinish();
            }

            @Override
            public void onStart() {
                super.onStart();
                Log.v(TAG, "请求开始");
            }

            @Override
            public void onSuccess(String content) {
                super.onSuccess(content);
                if (content == null) {
                    return;
                }
                JSONObject jsonObj = JSONObject.parseObject(content);
                JSONObject resData = (JSONObject) jsonObj.get("resData");
                if (resData == null) {
                    Log.v(TAG, "信息返回值为空");
                    return;
                }

                addproblem = JSONObject.parseObject(resData.toString(), AddProblemFeedback.class);

                if ("1".equals(addproblem.getResult())) {
                    Log.v("获取成功", "");
                    handler.sendEmptyMessage(11);
                } else {
                    handler.sendEmptyMessage(12);
                    Log.v("获取失败", "errorCode:" + addproblem.getErrorCode().toString() + "errorMsg:"
                            + addproblem.getErrorMsg().toString());
                }
            }
        });
    }

    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 11) {
                Loading.hideDialogForLoading();
                EmmApplication.Ts("您的反馈提交成功");
                finish();
            }
            if (msg.what == 12) {
                Loading.hideDialogForLoading();
                EmmApplication.Ts(addproblem.getErrorMsg().toString());
            }
        }

        ;
    };

    /**
     * <p>
     * <b>Title：</b> 异步处理图片
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 下午2:15:07
     */
    class RecordTaskUpdate extends AsyncTask<Void, Integer, Void> {

        @Override
        protected Void doInBackground(Void... arg0) {
            ArrayList<problemImageListinfo> problemImageList = new ArrayList<FeedBackActivity.problemImageListinfo>();
            Log.v(TAG, "EmmApplication.pir.size():" + EmmApplication.pir.size());
            for (int i = 0; i < EmmApplication.pir.size(); i++) {
                problemImageListinfo content = new problemImageListinfo();
                content.setProblemImageType(".jpg");
                content.setProblemImage(EmmApplication.setPatchRtString(EmmApplication.pir.get(i).sourcePath));
                problemImageList.add(content);
            }
            addProblemFeedback(problemImageList);
            return null;
        }

        // 当在上面方法中调用publishProgress时，该方法触发,该方法在I线程中被执行
        protected void onProgressUpdate(Integer... progress) {
        }

        protected void onPostExecute(Void result) {
        }

        protected void onPreExecute() {
        }
    }

    /**
     * 回调方法
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.w("a", +requestCode + "resultCode===" + resultCode + "RESULT_OK======" + RESULT_OK);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case PICK_FROM_CAMERA:
                String path = Album.parseResult(data).get(0);
                Log.w("a", "拍照:+>" + path);

                ImageItem item = new ImageItem();
                item.sourcePath = path;
                item.imageId = "1101841324";
                EmmApplication.pir.add(item);

                // 0不变 1删除
                if (null != EmmApplication.pir || EmmApplication.pir.size() > 0) {
                    if (null != ap) {
                        // ap.clear();
                    } else {
                        ap = new ArrayList<AddpirModel>();
                    }
                    if (EmmApplication.IsCreate) {// 是否新建，需要创建一个按钮
                        EmmApplication.IsCreate = false;
                        ap.clear();
                        AddpirModel a = new AddpirModel();
                        a.setIsnet("1");
                        a.setType("2");
                        a.setPath("");
                        ap.add(a);
                    }
                    for (int i = 0; i < EmmApplication.pir.size(); i++) {
                        int y = 0;
                        for (int n = 0; n < ap.size(); n++) {
                            if (EmmApplication.pir.get(i).sourcePath.equals(ap.get(n).getPath())) {
                                y++;
                            }
                        }
                        if (y > 0) {
                            Log.v(TAG, "已存在，不添加");
                        } else {
                            AddpirModel a = new AddpirModel();
                            a.setIsnet(EmmApplication.pir.get(i).type);
                            a.setType("1");
                            a.setPath(EmmApplication.pir.get(i).sourcePath);
                            ap.add(0, a);
                        }
                    }
                    adapter.SetDate(ap);
                }
                break;
            case 0:
                System.out.println("相册");
                break;
            default:
                break;
        }
    }
}
